package com.lz.yz.outing.controller;

import com.lz.yz.base.entity.ReturnValue;
import com.lz.yz.base.util.AudioUtil;
import com.lz.yz.outing.service.WechatService;
import com.lz.yz.outing.util.UploadOSSFile;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;


@RequestMapping("upload")
@Controller
public class UploadController {

    private Logger log = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    WechatService wechatService;

    @Autowired
    UploadOSSFile uploadOSSFile;

    /**
     * 文件上传
     *
     * @param remarkDescs
     * @return
     */
    @ApiOperation(value = "文件上传", response = ReturnValue.class)
    @RequestMapping(value = "saveFiles", method = RequestMethod.POST)
    @ResponseBody
    public ReturnValue saveFiles(@RequestParam("files") MultipartFile[] remarkDescs) {
        try {
            //允许上传的文件类型
            String fileType = "pdf,txt,xml,doc,docx,gif,png,bmp,jpg,jpeg,ppt,pptx";
            //允许上传的文件最大大小(20M,单位为byte)
            int maxSize = 1024 * 1024 * 20;

            StringBuilder consb = new StringBuilder();

            for (MultipartFile file : remarkDescs) {

                String fileName = file.getOriginalFilename();
                if (null == fileName || "".equals(fileName)) {
                    continue;
                }

                //判断文件大小是否超限
                if (file.getSize() > maxSize) {
                    return ReturnValue.generateFalseReturnValue("文件大小超过限制！应小于" + maxSize / 1024 / 1024 + "M");
                }
                //判断文件类型是否匹配
                String extName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase().trim();
                //判断是否为允许上传的文件类型
                if (!Arrays.asList(fileType.split(",")).contains(extName.toLowerCase())) {
                    return ReturnValue.generateFalseReturnValue("文件类型不正确，必须为" + fileType + "的文件！");
                }
                // 文件新路径
                String remarkDescUrl = uploadOSSFile.uploadFile(file.getInputStream(),
                        file.getOriginalFilename());
                consb.append(remarkDescUrl + ",");
            }
            if (consb != null && consb.length() > 0) {
                return ReturnValue.generateTrueReturnValue(consb.toString().substring(0, consb.lastIndexOf(",")));
            }
        } catch (Exception e) {
            log.error("文件上传异常,异常信息：{}", e);
        }
        return ReturnValue.generateTrueReturnValue("文件上传异常");
    }

    /**
     * 获取录音文件url
     */
    @ApiOperation(value = "获取录音文件url", response = ReturnValue.class)
    @RequestMapping(value = "getLocalUrl", method = RequestMethod.GET)
    @ResponseBody
    public ReturnValue getLocalUrl(String mediaId) {
        String url = null;
        try {
            url = this.handleVoice(mediaId);
        } catch (Exception e) {
            log.error("获取录音文件url异常,异常信息：{}", e);
        }
        return ReturnValue.generateTrueReturnValue(url);
    }


    /**
     * 从微信下载语音，并存储到硬盘
     */
    public String handleVoice(String mediaId) {
        String accessToken = wechatService.getAccessToken();
        InputStream is;
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
        File amrFile = null;
        File mp3File = null;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);

            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            // 获取文件转化为byte流
            if (!http.getContentType().equals("audio/amr")) {
                return null;
            }
            is = http.getInputStream();
            //存储到硬盘，原本音频格式为amr
            amrFile = File.createTempFile("temp", ".amr");
            UploadOSSFile.inputstreamtofile(is, amrFile);
            mp3File = File.createTempFile("temp", ".mp3");//创建临时文件
            //arm Convert Mp3
            AudioUtil.changeToMp3(amrFile, mp3File);
            InputStream in = new FileInputStream(mp3File);
            return uploadOSSFile.uploadFile(in, "temp.mp3");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            amrFile.deleteOnExit();
            mp3File.deleteOnExit();
        }
        return null;
    }


    /**
     * 图片上传
     *
     * @param imageFile
     * @return
     */
    @ApiOperation(value = "Base64图片上传", response = ReturnValue.class)
    @RequestMapping(value = "saveBase64Img", method = RequestMethod.POST)
    @ResponseBody
    public ReturnValue savePhoneRecover(String imageFile) {
        try {
            if (imageFile.indexOf("base64") == -1) {
                return ReturnValue.generateTrueReturnValue("data:image参数错误");
            }
            StringBuilder consb = new StringBuilder();
            // 文件新路径
            String remarkDescUrl = uploadOSSFile.uploadBase64File(imageFile);
            consb.append(remarkDescUrl + ",");
            if (consb != null && consb.length() > 0) {
                return ReturnValue.generateTrueReturnValue(consb.toString().substring(0, consb.lastIndexOf(",")));
            }
        } catch (Exception e) {
            log.error("Base64图片上传异常,异常信息：{}", e);
        }
        return ReturnValue.generateTrueReturnValue("Base64图片上传异常");
    }
}
